package com.ruoyi.web.service.Impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.domain.mes.*;
import com.ruoyi.web.domain.vo.CareOptionalVo;
import com.ruoyi.web.mapper.MesMachineCaredetailMapper;
import com.ruoyi.web.mapper.MesMachineCarereationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.mapper.MesMachineCareMapper;
import com.ruoyi.web.service.IMesMachineCareService;

import javax.annotation.Resource;
/**
 * 设备保养计划Service业务层处理
 *
 * @author levicash
 * @date 2024-01-16
 */
@Service
public class MesMachineCareServiceImpl implements IMesMachineCareService {
    @Resource
    private MesMachineCareMapper mesMachineCareMapper;

    @Resource
    private MesMachineCaredetailMapper mesMachineCaredetailMapper;

    /**
     * 查询设备保养计划
     *
     * @param id 设备保养计划主键
     * @return 设备保养计划
     */
    @Override
    public MesMachineCare selectMesMachineCareById(Long id) {
        return mesMachineCareMapper.selectMesMachineCareById(id);
    }

    /**
     * 查询设备保养计划列表
     *
     * @param mesMachineCare 设备保养计划
     * @return 设备保养计划
     */
    @Override
    public List<MesMachineCare> selectMesMachineCareList(MesMachineCare mesMachineCare) {
        return mesMachineCareMapper.selectMesMachineCareList(mesMachineCare);
    }

    /**
     * 新增设备保养计划
     *
     * @param mesMachineCare 设备保养计划
     * @return 时间间隔整数
     */
    @Transactional
    @Override
    public int insertMesMachineCare(MesMachineCare mesMachineCare) {
        mesMachineCare.setCreateBy(SecurityUtils.getUsername());
        mesMachineCare.setCreateTime(DateUtils.getNowDate());
        Integer intervalTimeNum = DateUtils.DateDiff(mesMachineCare.getStartTime(), mesMachineCare.getEndTime(), mesMachineCare.getCtype());
        String fullCode = "";
        if (!intervalTimeNum.equals(0)) {
            // 生成保养计划编号
            if (StringUtils.isEmpty(mesMachineCare.getCode())) {
                Date date = new Date();
                String codeFirst = "BYJH";
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String codeLast = dateFormat.format(date);
                fullCode = codeFirst.concat(codeLast);
                mesMachineCare.setCode(fullCode);
            }
            // 生成保养计划及关联设备
            int rows = mesMachineCareMapper.insertMesMachineCare(mesMachineCare);
            for (MesMachineCarereation reation : mesMachineCare.getMesMachineCarereationList()) {
                reation.setCreateBy(SecurityUtils.getUsername());
                reation.setCreateTime(DateUtils.getNowDate());
            }
            insertMesMachineCarereation(mesMachineCare);

            // 生成保养记录
            if (mesMachineCare.getHasDetail() != null) {
                if (mesMachineCare.getHasDetail() == 1) {
                    AddDetail(mesMachineCare);
                }

            }
        }
        return intervalTimeNum;
    }

    /**
     * 添加设备保养记录明细
     *
     * @param mesMachineCare 设备保养计划
     * @return 结果
     */
    @Transactional
    @Override
    public int AddDetail(MesMachineCare mesMachineCare) {

        Integer intervalTimeNum = DateUtils.DateDiff(mesMachineCare.getStartTime(), mesMachineCare.getEndTime(), mesMachineCare.getCtype());
        int count = 0;
        Date startDate = mesMachineCare.getStartTime();
        Date endDate = mesMachineCare.getEndTime();
        String intervalStr = mesMachineCare.getCtype();
        if ((intervalStr.equals("1") || intervalStr.equals("2")) && StringUtils.isEmpty(mesMachineCare.getPlanMultiple())) {
            return 0;
        }
        // 生成保养记录
        if (mesMachineCare.getHasDetail() == 1) {
            Random random = new Random();
            // 根据计划类型自动生成保养明细
            List<MesMachineCaredetail> listDetail = new ArrayList<>();
            //MesMachineCarereation machineCarereation = new MesMachineCarereation();
            //machineCarereation.setPlanCode(mesMachineCare.getCode());
            //List<MesMachineCarereation> reationList = mesMachineCarereationMapper.selectMesMachineCarereationList(machineCarereation);

            // 查询保养计划设备关联表
            List<MesMachineCarereation> reationList = mesMachineCare.getMesMachineCarereationList();

            // 自选计划 周计划、月计划
            if ((intervalStr.equals("1") || intervalStr.equals("2")) && StringUtils.isNotEmpty(mesMachineCare.getPlanMultiple())) {
                List<CareOptionalVo> listOptionalsALL = new ArrayList<>();

                int allDayCount = DateUtils.DateDiff(startDate, endDate, "0");
                // 自选周计划
                if (intervalStr.equals("1")) {
                    for (int i = 0; i < allDayCount; i++) {
                        Date currentDate = DateUtils.addDays(startDate, i);
                        int dayOfWeek = DateUtils.weekNoByDate(currentDate);
                        dayOfWeek = dayOfWeek - 1;
                        int dayNo = (dayOfWeek == 0) ? 7 : dayOfWeek;
                        CareOptionalVo OptionalModel = new CareOptionalVo();
                        OptionalModel.setOptionalNo(dayNo);
                        OptionalModel.setWeekName(DateUtils.weekNameByDate(currentDate));
                        OptionalModel.setCreateTime(currentDate);
                        OptionalModel.setOptionalType("周计划");
                        listOptionalsALL.add(OptionalModel);
                    }
                } else if (intervalStr.equals("2")) {
                    for (int i = 0; i < allDayCount; i++) {
                        Date currentDate = DateUtils.addDays(startDate, i);
                        int dayOfMonth = DateUtils.monthNoByDate(currentDate);
                        CareOptionalVo OptionalModel = new CareOptionalVo();
                        OptionalModel.setOptionalNo(dayOfMonth);
                        OptionalModel.setCreateTime(currentDate);
                        OptionalModel.setOptionalType("月计划");
                        listOptionalsALL.add(OptionalModel);
                    }
                }
                // 在时间段中，筛选选中日期
                String[] arrayCare = mesMachineCare.getPlanMultiple().split(",");
                List<String> listCare = Stream.of(arrayCare).collect(Collectors.toList());
                List<CareOptionalVo> ListOptionals = listOptionalsALL.stream().filter(t -> listCare.contains(String.valueOf(t.OptionalNo))).collect(Collectors.toList());

                for (CareOptionalVo OptionalsItem : ListOptionals) {
                    for (MesMachineCarereation item : reationList) {
                        MesMachineCaredetail detail = new MesMachineCaredetail();
                        detail.setCode(StringUtils.createCode(random));
                        detail.setPlanCode(mesMachineCare.getCode());
                        detail.setStartTime(OptionalsItem.getCreateTime());
                        detail.setStatus(compareDateStr(OptionalsItem.getCreateTime()));
                        detail.setCreateBy(SecurityUtils.getUsername());
                        detail.setCreateTime(DateUtils.getNowDate());
                        detail.setOperator(SecurityUtils.getUsername());
                        detail.setOperatorId(SecurityUtils.getUserId().toString());
                        detail.setMachineNo(item.getMachineNo());
                        detail.setRemark("保养计划自动生成");
                        detail.setDeptCode(mesMachineCare.getDeptCode());
                        detail.setDeptName(mesMachineCare.getDeptName());
                        listDetail.add(detail);

                    }
                }
            }
            // 非自选计划
            else {
                while (intervalTimeNum > 0) {
                    switch (intervalStr) {
                        case "0"://日计划
                            startDate = DateUtils.addDays(startDate, 1);
                            break;
                        case "3"://年计划
                            startDate = DateUtils.addYears(startDate, 1);
                            break;
                        case "4"://时计划
                            startDate = DateUtils.addHours(startDate, 1);
                            break;
                    }
                    intervalTimeNum = DateUtils.DateDiff(startDate, endDate, intervalStr);

                    for (MesMachineCarereation item : reationList) {
                        MesMachineCaredetail detail = new MesMachineCaredetail();
                        detail.setCode(StringUtils.createCode(random));
                        detail.setPlanCode(mesMachineCare.getCode());
                        detail.setStartTime(startDate);
                        detail.setStatus(compareDateStr(startDate));
                        detail.setCreateBy(SecurityUtils.getUsername());
                        detail.setCreateTime(DateUtils.getNowDate());
                        detail.setOperator(SecurityUtils.getUsername());
                        detail.setOperatorId(SecurityUtils.getUserId().toString());
                        detail.setMachineNo(item.getMachineNo());
                        detail.setRemark("保养计划自动生成");
                        detail.setDeptCode(mesMachineCare.getDeptCode());
                        detail.setDeptName(mesMachineCare.getDeptName());
                        listDetail.add(detail);
                    }
                }
            }
            // 批量新增改保养计划的保养记录
            if (listDetail.size() > 0) {
                count = mesMachineCaredetailMapper.batchMesMachineCaredetail(listDetail);
            }
        }
        // 更新保养计划是否有保养记录字段
        MesMachineCare machineCare = new MesMachineCare();
        machineCare.setCode(mesMachineCare.getCode());
        List<MesMachineCare> modeList = mesMachineCareMapper.selectMesMachineCareMode(machineCare);
        MesMachineCare mode = modeList.get(0);
        mode.setHasDetail(1);
        mesMachineCareMapper.updateMesMachineCare(mode);
        return count;
    }

    /**
     * 校验保养计划编号是否存在
     *
     * @param planCode 计划编号
     * @return boolean
     */
    public boolean checkDeviceCareUnique(String planCode) {
        MesMachineCare machineCare = new MesMachineCare();
        machineCare.setCode(planCode);
        List<MesMachineCare> modeList = mesMachineCareMapper.selectMesMachineCareMode(machineCare);
        if (modeList.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 比较参数时间的日期部分和当前时间的日期部分是否相等
     *
     * @param date 传入时间
     * @return 数值
     */
    public int compareDateStr(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateNow = new Date();
        String compareFirst = dateFormat.format(date);
        String compareLast = dateFormat.format(dateNow);
        int status = compareFirst.equals(compareLast) ? 1 : 0;
        return status;
    }

    /**
     * 修改设备保养计划
     *
     * @param mesMachineCare 设备保养计划
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMesMachineCare(MesMachineCare mesMachineCare) {
        mesMachineCare.setUpdateBy(SecurityUtils.getUsername());
        mesMachineCare.setUpdateTime(DateUtils.getNowDate());
        mesMachineCareMapper.deleteMesMachineCarereationByPlanCode(mesMachineCare.getCode());
        insertMesMachineCarereation(mesMachineCare);
        return mesMachineCareMapper.updateMesMachineCare(mesMachineCare);
    }

    /**
     * 批量删除设备保养计划
     *
     * @param ids 需要删除的设备保养计划主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesMachineCareByIds(Long[] ids) {
        List<String> codes = new ArrayList<>();
        List<MesMachineCare> list = mesMachineCareMapper.selectMesMachineCareByIds(ids);
        if (list.size() > 0) {
            for (MesMachineCare item : list) {
                codes.add(item.getCode());
            }
            String array[] = codes.toArray(new String[0]);
            // 根据保养记录编号删除保养计划关联设备表
            mesMachineCareMapper.deleteMesMachineCarereationByPlanCodes(array);
            // 根据保养记录编号删除设备保养记录
            mesMachineCareMapper.deleteMesMachineCaredetailByPlanCodes(array);
        }

        return mesMachineCareMapper.deleteMesMachineCareByIds(ids);
    }

    /**
     * 删除设备保养计划信息
     *
     * @param id 设备保养计划主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesMachineCareById(Long id) {
        MesMachineCare mesMachineCare = mesMachineCareMapper.selectMesMachineCareById(id);
        mesMachineCareMapper.deleteMesMachineCarereationByPlanCode(mesMachineCare.getCode());
        return mesMachineCareMapper.deleteMesMachineCareById(id);
    }

    /**
     * 新增设备计划关联信息
     *
     * @param mesMachineCare 设备保养计划对象
     */
    public void insertMesMachineCarereation(MesMachineCare mesMachineCare) {
        List<MesMachineCarereation> mesMachineCarereationList = mesMachineCare.getMesMachineCarereationList();
        String planCode = mesMachineCare.getCode();
        if (StringUtils.isNotNull(mesMachineCarereationList)) {
            List<MesMachineCarereation> list = new ArrayList<MesMachineCarereation>();
            for (MesMachineCarereation mesMachineCarereation : mesMachineCarereationList) {
                mesMachineCarereation.setPlanCode(planCode);
                list.add(mesMachineCarereation);
            }
            if (list.size() > 0) {
                mesMachineCareMapper.batchMesMachineCarereation(list);
            }
        }
    }

    /**
     * 修改保养计划状态
     *
     * @param mesMachineCare 保养计划
     * @return 结果
     */
    @Override
    public int updateMesMachineCareStatus(MesMachineCare mesMachineCare) {
        int count = mesMachineCareMapper.updateMesMachineCare(mesMachineCare);
        MesMachineCaredetail machineCaredetail = new MesMachineCaredetail();
        // 停用
        if (mesMachineCare.getStatus() == 1) {
            machineCaredetail.setPlanCode(mesMachineCare.getCode());
            machineCaredetail.setStatus(3);
            Map<String, Object> map = new HashMap<>();
            map.put("statusMark", 2); // 排除已执行
            machineCaredetail.setParams(map);
        }
        // 启用
        else if (mesMachineCare.getStatus() == 0) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dateNow = new Date();
            String timeFormat = dateFormat.format(dateNow);
            machineCaredetail.setPlanCode(mesMachineCare.getCode());
            machineCaredetail.setStatus(0);
            Map<String, Object> map = new HashMap<>();
            switch (mesMachineCare.getCtype()) {
                case "0"://日计划
                    map.put("timeMarkDate", timeFormat);
                    break;
                case "1"://周计划
                    map.put("timeMarkAll", timeFormat);
                    break;
                case "2"://月计划
                    map.put("timeMarkAll", timeFormat);
                    break;
                case "3"://年计划
                    map.put("timeMarkAll", timeFormat);
                    break;
                case "4"://时计划
                    map.put("timeMarkDate", timeFormat);
                    map.put("timeMarkHour", timeFormat);
                    break;
            }
            machineCaredetail.setParams(map);
        }
        // 根据计划编号和计划保养时间等批量更新保养记录
        mesMachineCaredetailMapper.updateMesMachineCaredetailStatus(machineCaredetail);
        return count;
    }

}
